<style lang="scss">
@import "./uv.scss";
</style>
<template>
  <view class="add-address ">
    <u-cityPopup :form="dpdzPopupForm" @chooseChange="provinceCityAreaChange" ref="cityPopup"></u-cityPopup>
    <u-my-layOut :showNavbar="false" :navbarOption="{ bgColor: 'rgba(255,255,255,1)', title: '订单', border: true }" :color="{ statusBarHeightColor: '#f6f4f7' }">
      <template v-slot:header>
        <uv-navbar @leftClick="leftClick" title="" bgColor="#F6F4F7" :safeAreaInsetTop="false" :fixed="false" imgMode="widthFix" />
      </template>
      <template v-slot:main>
        <view class="content pl30 pr30">
          <div class="title ">{{routeQuery.id > -1 ? '修改常用地址信息' : '新建地址'}}</div>
          <view class="box ">
            <div class="pl30">
              <uv-form :rules="rules" :model="model1" ref="addressForm" labelWidth="60">
                <uv-form-item label="地区" required prop="addressForm.provinceCityArea">
                  <div class="" @click="openTap" style="width: 100%">
                    <uv-input v-model="model1.addressForm.provinceCityArea" border="none" readonly suffixIcon="arrow-right" suffixIconStyle="color:#C9CACA" placeholder="点击搜索地区" placeholderStyle="color:#727171;font-size:30rpx">
                      <template v-slot:suffix>
                        <uv-icon name="arrow-right"></uv-icon>
                      </template>
                    </uv-input>
                  </div>
                </uv-form-item>
                <!-- <uv-form-item label="地址" required prop="addressForm.provinceCityArea">
							<div class="dz" @click="openTap" style="width: 100%">
								<uv-input v-if="!model1.addressForm.address" v-model="model1.addressForm.address" border="none" readonly
									suffixIcon="arrow-right" suffixIconStyle="color:#C9CACA" placeholder="点击搜索地址"
									placeholderStyle="color:#727171;font-size:30rpx" />
								<div v-if="model1.addressForm.address">
									<div class="" style="">
										<div style="width: 60vw!important;" class="title1 fz34 single-line">
											{{model1.addressForm.list.title}}</div>
										<div style="width: 60vw!important;" class="desc fz28 single-line">
											{{model1.addressForm.list.address}}</div>
									</div>
									<div class="jt">
										<uv-icon name="arrow-right"></uv-icon>
									</div>
								</div>
							</div>
						</uv-form-item> -->
                <uv-form-item label="地址" required prop="addressForm.storey">
                  <uv-input v-model="model1.addressForm.storey" border="none" placeholder="详细地址">
                    <!-- <template v-slot:suffix>
									<uv-icon @click="addressTap" name="map"></uv-icon>
								</template> -->
                  </uv-input>
                </uv-form-item>
                <uv-form-item label="门牌号">
                  <uv-input v-model="model1.addressForm.house_number" border="none" placeholder="单元、门牌号，如：4单元201"></uv-input>
                </uv-form-item>
                <uv-form-item label="联系人" required prop="addressForm.name">
                  <uv-input v-model="model1.addressForm.name" border="none" placeholder="联系人姓名" />
                </uv-form-item>
                <uv-form-item label="电话" required prop="addressForm.tel">
                  <uv-input v-model="model1.addressForm.tel" border="none" placeholder="联系人号码" />
                </uv-form-item>
              </uv-form>
            </div>
          </view>
        </view>
      </template>
      <template v-slot:footer>
				<div class="pb30">
        <div class="xjdz ml30 mr30 bsbb"   @click="submitTap">保存</div>
					
				</div>
      </template>
    </u-my-layOut>
    <u-dpdzPopup @choose="chooseTap" ref="dpdzPopupVue"></u-dpdzPopup>
  </view>
</template>
<script>
import { addPickupAddress, addAddress, getNearbyPlaces, getAddressList, editAddress, editPickupAddress, setDefault, getAddressDetail, pickupAddressInfo } from '@/api'
import dpdzPopupVue from '@/components/dpdzPopup.vue'
import cityPopup from './cityPopup.vue'
import { objectToUrlParams } from '@/util/tools.js'
import myLayOutVue from "./components/layOut.vue";
export default {
  components: {
    "u-my-layOut": myLayOutVue,
    "u-dpdzPopup": dpdzPopupVue, "u-cityPopup": cityPopup
  },
  data() {
    return {
      routeQuery: {},
      form: {
        page: 1,
        limit: 20,
        lat: 32.455778,
        lng: 119.923116,
        keywords: ''
      },
      model1: {
        addressForm: {
          tel: null,
          name: null,
          house_number: '',
          address: '',
          provinceCityArea: ''
        },
      },
      rules: {

        'addressForm.provinceCityArea': {
          type: 'string',
          required: true,
          message: '请填写地区',
          trigger: ['blur', 'change']
        },
        'addressForm.storey': {
          type: 'string',
          required: true,
          message: '请填写地址',
          trigger: ['blur', 'change']
        },

        'addressForm.name': {
          type: 'string',
          required: true,
          message: '请填写联系人',
          trigger: ['blur', 'change']
        },
        'addressForm.tel': {
          type: 'string',
          required: true,
          validator: (rule, value, callback) => {
            return uni.$uv.test.mobile(value)
          },
          message: '电话号码格式错误',
          trigger: ['blur']
        },
      },
      total: 0,
      page: 1, limit: 50,
      tableData: [],
      dpdzPopupForm: {}
    }
  },
  // onShow() {
  // 	try {
  // 		wx.authorize({
  // 			scope: 'scope.userLocation',
  // 			success() {
  // 				console.log('用户已经同意小程序使用位置信息')
  // 				wx.getLocation({
  // 					type: 'wgs84',
  // 					success: function (res) {
  // 						console.log('当前位置的经度：' + res.longitude);
  // 						console.log('当前位置的纬度：' + res.latitude);
  // 					},
  // 					fail(err) {
  // 						console.error(err, '====')
  // 					}
  // 				});
  // 				// wx.getLocation({
  // 				// 	type: 'wgs84',
  // 				// 	success(res) {
  // 				// 		console.log(res.latitude, res.longitude)
  // 				// 	},
  // 				// 	fail(err) {
  // 				// 		console.error(err, '====')
  // 				// 	}
  // 				// })
  // 			},
  // 			fail() {
  // 				// 用户拒绝授权
  // 				wx.showModal({
  // 					title: '提示',
  // 					content: '请同意授权位置信息',
  // 					showCancel: false,
  // 					success(modalSuccess) {
  // 						if (modalSuccess.confirm) {
  // 							wx.openSetting({
  // 								success(res) {
  // 									// 成功打开设置页面并返回当前权限状态
  // 									console.log(res.authSetting);
  // 									// 例如：查看位置权限是否开启
  // 									if (res.authSetting['scope.userLocation']) {
  // 										console.log('位置权限已开启');
  // 									}
  // 								},
  // 								fail(err) {
  // 									// 打开设置页面失败
  // 									console.error('打开设置失败：', err);
  // 								}
  // 							})
  // 						}
  // 					}
  // 				})
  // 			}
  // 		})
  // 	} catch (error) {

  // 	}

  // 	// wx.getSetting({
  // 	// 	success(res) {
  // 	// 		if (!res.authSetting['scope.userLocation']) {
  // 	// 			wx.authorize({
  // 	// 				scope: 'scope.userLocation',
  // 	// 				success() {
  // 	// 					console.log(res.authSetting, 123)
  // 	// 					wx.getLocation({
  // 	// 						type: 'wgs84',
  // 	// 						success(res) {
  // 	// 							console.log(res, '=====')
  // 	// 						},
  // 	// 						fail(err) {
  // 	// 							console.log(err)
  // 	// 						}
  // 	// 					})
  // 	// 					// 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
  // 	// 				}
  // 	// 			})
  // 	// 		}
  // 	// 	}
  // 	// })

  // },
  onLoad(options) {
    if (options) this.routeQuery = options
    this.initPage()
    console.log(getCurrentPages()); // 打印当前页面栈层级
  },
  methods: {
    provinceCityAreaChange(item) {
      let { province, city, area, district } = item
      let provinceCityArea = (province.title ? province.title : '') + (city.title ? '/' + city.title : '') + (area.title ? '/' + area.title : '') + (district.title ? '/' + district.title : '')
      this.$set(this.model1.addressForm, 'provinceCityArea', provinceCityArea)
      this.$set(this.model1.addressForm, 'province', province.title)
      this.$set(this.model1.addressForm, 'city', city.title)
      this.$set(this.model1.addressForm, 'area', area.title)
      this.$set(this.model1.addressForm, 'district', district.title)
      this.dpdzPopupForm = JSON.parse(JSON.stringify(this.model1.addressForm))
    },
    leftClick() {
      console.log(getCurrentPages().length)
      uni.navigateBack({ url: objectToUrlParams('/pages-user/address', this.routeQuery) });
    },
    submitTap() {
      this.$refs.addressForm.validate().then(res => {
        let form = JSON.parse(JSON.stringify(this.model1.addressForm))
        if (!form.district) return uni.$uv.toast('请选择街道')
        form.province = form.province
        form.town = form.district
        form.area = form.area
        form.city = form.city
        form.storey = form.storey
        delete form.provinceCityArea
        delete form.district
        uni.showLoading({ title: '加载中', mask: true })
        if (this.routeQuery.id) {
          if (this.routeQuery.dzb === 'Q') {
            editPickupAddress(this.routeQuery.id, form).then(res => {
              uni.hideLoading()
              if (res.code === 200) uni.navigateBack({ url: objectToUrlParams('/pages-user/address', this.routeQuery) });
            })
          } else {
            editAddress(this.routeQuery.id, form).then(res => {
              uni.hideLoading()
              if (res.code === 200) uni.navigateBack({ url: objectToUrlParams('/pages-user/address', this.routeQuery) });
            })
          }
        } else {
          if (this.routeQuery.dzb === 'Q') {
            addPickupAddress(form).then(res => {
              this._addressApi(res, form)
            })
          } else {
            addAddress(form).then(res => {
              this._addressApi(res, form)
            })
          }
        }
      })
    },
    navigationFun(pageUrl) {
      var cps = getCurrentPages();
      var delta = 0;
      for (var i = cps.length - 1; i >= 0; i--) {
        if (cps[i].route === pageUrl) {
          if (delta === 0) {
            return;
          }
          wx.navigateBack({
            delta: delta
          });
          return;
        }
        delta++;
      }
      wx.navigateTo({
        url: pageUrl
      });
    },
    _addressApi(res, form) {
      let key = this.routeQuery.dzb
      uni.hideLoading()
      if (res.code === 200) {
        form.id = res.result
        if (!this.routeQuery.type) {
          uni.removeStorage({ key: 'dzb' });
          uni.navigateBack({ url: '/pages-user/address' });
          return
        }
        uni.navigateBack({ url: objectToUrlParams('/pages-user/address', this.routeQuery) });
      
      }
    },

    chooseTap(item) {
      console.log(item)
      let provinceCityArea = (item.province ? item.province : '') + (item.city ? '/' + item.city : '') + (item.district ? '/' + item.district : '')
      this.$set(this.model1.addressForm, 'provinceCityArea', provinceCityArea)
      this.$set(this.model1.addressForm, 'province', item.province)
      this.$set(this.model1.addressForm, 'city', item.city)
      this.$set(this.model1.addressForm, 'district', item.district)
      this.$set(this.model1.addressForm, 'storey', item.title)
      this.$set(this.model1.addressForm, 'address', item.address)
      this.dpdzPopupForm = item
    },
    searchTap() {
      this.$set(this.form, 'page', 1)
      this.$set(this.form, 'limit', 20)
      this.tableData = []
      this._getNearbyPlaces()

    },
    onReachBottom() {
      if (this.total > this.tableData.length) {
        let page = this.form.page
        this.$set(this.form, 'page', page + 1)
        this._getNearbyPlaces()
      }
    },

    openTap() {
      // this.$refs.dpdzPopupVue.open()
      this.$refs.cityPopup.openFun()

    },
    addressTap() {
      this.$refs.dpdzPopupVue.open()

    },
    closeTap() {
      this.$nextTick(() => {
        this.$refs.popup.close();
      })
    },
    change() { },
    tabTap() {
      wx.navigateTo({
        url: './set-address',
      });
    },
    _initData(res) {
      let dpdzPopupForm = {
        id: res.result.id,
        province: res.result.province,
        district: res.result.town,
        area: res.result.area,
        name: res.result.name,
        house_number: res.result.house_number,
        tel: res.result.tel,
        city: res.result.city,
        storey: res.result.storey,
        address: res.result.address,
      }
      let provinceCityArea = (dpdzPopupForm.province ? dpdzPopupForm.province : '') + (dpdzPopupForm.city ? '/' + dpdzPopupForm.city : '') + (dpdzPopupForm.area ? '/' + dpdzPopupForm.area : '') + (dpdzPopupForm.district ? '/' + dpdzPopupForm.district : '')
      dpdzPopupForm.provinceCityArea = provinceCityArea
      this.$set(this.model1, 'addressForm', dpdzPopupForm)
      this.dpdzPopupForm = dpdzPopupForm
      uni.hideLoading()
    },
    initPage() {
      if (this.routeQuery.id) {
        uni.showLoading({ title: '加载中', mask: true })
        if (this.routeQuery.dzb === 'Q') {
          pickupAddressInfo(this.routeQuery.id).then(res => {
            if (res.code === 200) this._initData(res)
          })
        } else {
          getAddressDetail(this.routeQuery.id).then(res => {
            if (res.code === 200) this._initData(res)
          })
        }

      }

    },
    _getNearbyPlaces() {
      uni.showLoading({ title: '加载中', mask: true })
      getNearbyPlaces(this.form).then(res => {
        if (res.code === 200) {
          uni.hideLoading()
          this.total = res.result.total
          this.tableData = this.tableData.concat(res.result.data)
        }
      })
    }
  }

}
</script>

<style lang="scss">
page {
  background-color: #f6f4f7;
}
</style>

<style lang="scss" scoped>
.add-address {

  .dz {
    min-height: 48rpx;
    position: relative;
    overflow: hidden;

    .jt {
      position: absolute;
      margin-left: 100%;
      top: 50%;
      transform: translate(-97%, -50%);
    }
  }

  .title {
    font-weight: bold;
    font-size: 38rpx;
    color: #333333;
    box-sizing: border-box;
  }

  .title1 {
    font-size: 28rpx;
    color: #333333;
    padding-right: 20rpx;
    width: 95%;
  }

  .desc {
    font-size: 26rpx;
    color: #adadae;
    padding-right: 20rpx;
    padding-top: 10rpx;
    width: 95%;
    box-sizing: border-box;
  }

  .xzwz {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 20rpx;
    padding-bottom: 20rpx;
    padding-right: 30rpx;
    padding-left: 40rpx;
    border-bottom: 2rpx solid #eeeeee;
  }

  .xzwz1 {
    padding: 20rpx;
    border-bottom: 2rpx solid #eeeeee;
  }

  .content {
    .box {
      padding: 30rpx;
      margin-top: 30rpx;
      margin-bottom: 50rpx;
      border-radius: 20rpx;
      background-color: #fff;
      overflow: hidden;
    }
  }

  .popup-content {
    padding-top: 30rpx;
    height: 60vh;
    background-color: #fff;
  }

  .xjdz {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 90rpx;
    background: #de0012;
    font-weight: 600;
    font-size: 36rpx;
    color: #ffffff;
    border-radius: 50rpx;
		box-sizing: border-box;
		margin-left: 30rpx;
		margin-right: 30rpx;
  }
}
</style>